# Maintainer: Ray Donnelly <mingw.android@gmail.com>

_realname=SuiteSparse
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-suitesparse")
pkgver=4.4.4
pkgrel=1
pkgdesc='A suite of sparse matrix algorithms (mingw-w64)'
license=('GPL')
arch=('any')
source=("http://faculty.cse.tamu.edu/davis/${_realname}/${_realname}-${pkgver}.tar.gz"
        "0001-Win32-Do-not-link-librt.patch"
        "0002-Win32-Add-strip-trailing-cr-to-diff-for-crlf.patch"
        "0003-MSYS2-Use-OpenBLAS.patch"
        "0004-Allow-env-specified-INSTALL_LIB-and-INSTALL_INCLUDE.patch")
depends=("${MINGW_PACKAGE_PREFIX}-openblas")
makedepends=("${MINGW_PACKAGE_PREFIX}-gcc-fortran")
options=('staticlibs')
sha256sums=('f2ae47e96f3f37b313c3dfafca59f13e6dbc1e9e54b35af591551919810fb6fd'
            '873590a9a5583a441324c7755ce8c2bbf6d121e445f2f44cc858d871cb24c03c'
            'ec30bb1ba5adb9ec23335be1435ca4587633e82f0dda1673c92272b458306e3f'
            'd1a4cf365782c890fe0d226b643c45eccd87f648b8b4658ca9bb226db5f137c0'
            'd65499e77e600140d784f6e8c9db80e610419126c7837bfba89898c5a6baa0ba')

prepare() {
  cd "${srcdir}"/${_realname}
  patch -p1 -i "${srcdir}"/0001-Win32-Do-not-link-librt.patch
  patch -p1 -i "${srcdir}"/0002-Win32-Add-strip-trailing-cr-to-diff-for-crlf.patch
  patch -p1 -i "${srcdir}"/0003-MSYS2-Use-OpenBLAS.patch
  patch -p1 -i "${srcdir}"/0004-Allow-env-specified-INSTALL_LIB-and-INSTALL_INCLUDE.patch
}

build() {
  [[ -d "${srcdir}"/build-${CARCH} ]] && rm -rf "${srcdir}"/build-${CARCH}
  cp -rf "${srcdir}"/${_realname} build-${CARCH}
  cd "${srcdir}"/build-${CARCH}

  # Make twice due to missing dependencies
  # between CHOLMOD/Lib and kluldemo
  for _dir in ${PWD}/CHOLMOD/Lib ${PWD}; do
    pushd ${_dir}
      # https://www.gnu.org/software/octave/doc/interpreter/Compiling-Octave-with-64_002dbit-Indexing.html says
      # "On 64-bit Windows systems, use -DLONGBLAS="long long" instead.", but that seems wrong. If 64-bit indexing
      # is wanted, then long long should be used on 32-bit Windows too I expect (unless LONGBLAS refers to pointer
      # size in some instances?)
      CFLAGS='-DLONGBLAS="long long"' \
      CXXFLAGS='-DLONGBLAS="long long"' \
      CC=gcc CXX=g++ \
        make
    popd
  done
}

package() {
  cd "${srcdir}"/build-${CARCH}

  mkdir -p "${pkgdir}"${MINGW_PREFIX}/{lib,include}
  make install \
    INSTALL_LIB="${pkgdir}"${MINGW_PREFIX}/lib \
    INSTALL_INCLUDE="${pkgdir}"${MINGW_PREFIX}/include

  # Remove all the version-named static libraries. They'd be symlinks
  # on other systems.
  find "${pkgdir}"${MINGW_PREFIX} -name "*.*.*.*.a" -exec rm -f {} \;
}
